﻿package framework.core;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtil
{
	private String mailServer = "";
	private String mailFromAddr = "";
	private String mailUser   = "";
	private String mailPassword = "";
	private String mailAuth = "";
	public String getMailFromAddr()
	{
		return mailFromAddr;
	}
	public void setMailFromAddr(String mailFromAddr)
	{
		this.mailFromAddr = mailFromAddr;
	}
	public String getMailPassword()
	{
		return mailPassword;
	}
	public void setMailPassword(String mailPassword)
	{
		this.mailPassword = mailPassword;
	}
	public String getMailServer()
	{
		return mailServer;
	}
	public void setMailServer(String mailServer)
	{
		this.mailServer = mailServer;
	}
	public String getMailUser()
	{
		return mailUser;
	}
	public void setMailUser(String mailUser)
	{
		this.mailUser = mailUser;
	}
	public String getMailAuth()
	{
		return mailAuth;
	}
	public void setMailAuth(String mailAuth)
	{
		this.mailAuth = mailAuth;
	}
	
	// 构造
	public MailUtil() throws Exception{
		setMailServer(Config.getMailServer());
		setMailFromAddr(Config.getMailFromAddr());
		setMailUser(Config.getMailUser());
		setMailPassword(Config.getMailPassword());
		setMailAuth(Config.getMailAuth());
	}
	
	// 发送邮件 , 不支持抄送和暗送
	public void sendMail(String toAddr, String subject, String content) throws Exception
	{
		try
		{
			Properties props = new Properties();
			props.put("mail.smtp.host", getMailServer());
			props.put("mail.smtp.auth", getMailAuth());
			
			// 建立会话并且认证
			Session mailSession = Session.getDefaultInstance(props,
					new Authenticator()
					{
						public PasswordAuthentication getPasswordAuthentication()
						{
							return new PasswordAuthentication(getMailUser(), getMailPassword());
						}
					});
			
			// 打印log至console
			//mailSession.setDebug(true);
			
			
			Message mailMessage = new MimeMessage(mailSession);
			mailMessage.setFrom(new InternetAddress(getMailFromAddr()));	// 发件人
			mailMessage.addRecipient(Message.RecipientType.TO,new InternetAddress(toAddr));//收件人
			mailMessage.setContent(content, "text/html;charset=gb2312"); // 设置为HTML邮件内容
			mailMessage.setSubject(subject);		// 主题
//		mailMessage.setText(content);			// 内容，只支持简单邮件
			mailMessage.saveChanges();
			
			Transport transport = mailSession.getTransport("smtp"); 
			transport.connect(getMailServer(), getMailUser(), getMailPassword()); 
			transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); 
			transport.close();
		} catch (Exception e)
		{
			//e.printStackTrace();
			throw new BizException("邮件发送失败！\\n请检查您的E-Mail地址。\\n---------------------\\n若重复出现此情况请与系统管理员联系。");
		} 
	}

}
